package cn.com.jonpad.demo03j_jpa;

import cn.com.jonpad.demo03j_jpa.entity.City;
import cn.com.jonpad.demo03j_jpa.entity.QCity;
import cn.com.jonpad.demo03j_jpa.entity.QHotel;
import cn.com.jonpad.demo03j_jpa.repository.CityRepository;
import cn.com.jonpad.demo03j_jpa.service.CityAndHotelService;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

/**
 * @author Jon Chan
 * @date 2019/1/21 17:22
 */
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class QueryDsl {
    @Autowired
    private CityRepository cityRepository;
    @Autowired
    private CityAndHotelService cityAndHotelService;

    /**
     * 单表动态分页查询
     */
    @Test
    public void testQueryDsl() {
        //动态条件
        QCity qCity = QCity.city;
        //该Predicate为querydsl下的类,支持嵌套组装复杂查询条件
        Predicate predicate = qCity.id.longValue().lt(3)
                .and(qCity.name.like("shanghai"));
        //分页排序
        Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC, "id"));
        PageRequest pageRequest = new PageRequest(0, 10, sort);
        Page<City> tCityPage = cityRepository.findAll(predicate, pageRequest);
        log.info("{}", tCityPage.getTotalElements());
    }

    @Test
    public void testfindCityAndHotel() {
        QCity qtCity = QCity.city;
        QHotel qtHotel = QHotel.hotel;
        //查询条件
        Predicate predicate = qtCity.name.like("shanghai");

        //调用
        List<Tuple> result = cityAndHotelService.findCityAndHotel(predicate);
        //对多元组取出数据,这个和select时的数据相匹配
        for (Tuple row : result) {
            System.out.println("qtCity:"+row.get(qtCity));
            System.out.println("qtHotel:"+row.get(qtHotel));
            System.out.println("--------------------");
        }
        System.out.println(result);
    }
}
